package com.muqi.app.qlearn.student.ui;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.data.RadarDataSet;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.NumberFormatUtil;

import com.muqi.app.qlearn.modles.GrowData;
import com.muqi.app.qlearn.modles.GrowRewardAndMoveInfo;
import com.muqi.app.qlearn.student.BaseStudentActivity;
import com.muqi.app.qlearn.student.CompetitionActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.MyClassStudent;
import com.muqi.app.user.widget.ClassWithStudentsWindow;

public class GrowthReportActivity extends BaseStudentActivity implements
		OnClickListener,ClassWithStudentsWindow.SelectCWithSListener  {

	private BarChart mChart_reward;
	private BarChart mChart_move;
	

	private RadarChart mRadarChart_reward;
	private RadarChart mRadarChart_move;
	
	private Button mBt_com;
	private Button mBt_arc;
	private TextView mTv_reward_time;
	private TextView mTv_move_time;

	private TextView mTv_reward_title;
	private TextView mTv_move_title;

	private TextView mTv_reward_introduce;
	private TextView mTv_move_introduce;

	private TextView tv_title;

	private String startTime;
	private String endTime;
	
	private List<GrowRewardAndMoveInfo> infos;
	
	private ClassWithStudentsWindow myStudentsWindow = null;
	private TreeRefreshReceiver receiver = null;
	private String student_id;
	private int type=2;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_growth_report);

	}

	@Override
	protected void onInit() {
		super.onInit();
		mChart_move = (BarChart) findViewById(R.id.barchart_move);
		mChart_reward = (BarChart) findViewById(R.id.barchart_reward);
		
		mRadarChart_reward = (RadarChart) findViewById(R.id.ward_chart);
		mRadarChart_move = (RadarChart) findViewById(R.id.move_chart);
		
		mTv_move_introduce = (TextView) findViewById(R.id.tv_move_introduce);
		mTv_reward_introduce = (TextView) findViewById(R.id.tv_reward_introduce);

		mTv_move_time = (TextView) findViewById(R.id.tv_grow_move_time);
		mTv_reward_time = (TextView) findViewById(R.id.tv_grow_reward_time);

		mTv_move_title = (TextView) findViewById(R.id.tv_move_title);
		mTv_reward_title = (TextView) findViewById(R.id.tv_reward_title);

		mBt_arc = (Button) findViewById(R.id.bt_grow_Academic);
		mBt_com = (Button) findViewById(R.id.bt_grow_com);

		tv_title = (TextView) findViewById(R.id.tv_title);

		mBt_arc.setOnClickListener(this);
		mBt_com.setOnClickListener(this);

		SimpleDateFormat format = new SimpleDateFormat("yyyy.M.d");
		Calendar calendar = Calendar.getInstance();

		if (calendar.get(Calendar.MONTH) + 1 <= 9) {
			startTime = (calendar.get(Calendar.YEAR) - 1) + ".9.1";
			endTime = format.format(calendar.getTime());
		} else {
			startTime = (calendar.get(Calendar.YEAR)) + ".9.1";
			endTime = format.format(calendar.getTime());
		}
		tv_title.setText(mSpUtil.getCurrentChildName() + "成长报告");
		tv_title.setOnClickListener(this);
		
		mTv_move_time.setText(startTime + "-" + endTime);
		mTv_reward_time.setText(startTime + "-" + endTime);
		initChart(mChart_move);
		initChart(mChart_reward);
		
		if (currentChild != null) {
			setMyclassStudentsWindow(currentChild);
		}

		receiver = new TreeRefreshReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MContants.REFRESH_FILETREE_ACTION);
		filter.addAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		registerReceiver(receiver, filter);
		student_id=mSpUtil.getCurrentChildId();
		

	}

	@Override
	protected void onData() {
		getRewardStatis();
		getMoveStatis();

	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.bt_grow_Academic:
			intent = new Intent(this, CompetitionActivity.class);
			intent.putExtra("uiType", 0);
			startActivity(intent);
			break;
		case R.id.bt_grow_com:
			intent = new Intent(this, CompetitionActivity.class);
			intent.putExtra("uiType", 1);
			startActivity(intent);
			break;
		case R.id.tv_title:
			/*if (myStudentsWindow != null) {
				myStudentsWindow.showPopupWindow(v);
			}*/
			break;
		default:
			break;
		}

	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		// TODO Auto-generated method stub

	}

	/**
	 * 获奖统计 综合素质
	 */
	private void getRewardStatis() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", student_id);
		sendMap.put("start_date", startTime);
		sendMap.put("end_date", endTime);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.GET_GROW_REWORD_STATISC, sendMap);

		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					// Log.e("===", result);
                            
					infos = ResponseUtils.getGrowStatisticsInfos(mContext,
							result);
					if (infos != null) {
						if(type==1){
							showChart(mRadarChart_reward, infos);
						}else{
							showChart(mChart_reward, infos);
						}
						
					}
					

				}

			}

		});

	}

	/**
	 * 活动统计 综合素质
	 */
	private void getMoveStatis() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", student_id);
		sendMap.put("start_date", startTime);
		sendMap.put("end_date", endTime);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.GET_GROW_MOVE_STATISC, sendMap);

		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					// Log.e("===", result);
					infos = ResponseUtils.getGrowStatisticsInfos(mContext,
							result);
					if (infos != null) {
						if(type==1){
							showChart(mRadarChart_move, infos);
						}else{
							showChart(mChart_move, infos);
						}
						
					}
					

				}

			}

		});

	}

	private void initChart(BarChart mChart) {
		mChart.setTouchEnabled(false);
		mChart.setDrawBarShadow(false);
		mChart.setDrawValueAboveBar(true);
		mChart.setDescription("");
		mChart.setMaxVisibleValueCount(60);

		mChart.setPinchZoom(false);
		mChart.setDrawGridBackground(false);

		XAxis xAxis = mChart.getXAxis();
		xAxis.setPosition(XAxisPosition.BOTTOM);
		xAxis.setDrawGridLines(false);
		xAxis.setSpaceBetweenLabels(2);
		xAxis.setTextColor(getResources().getColor(R.color.statis_reword_color));
		xAxis.setTextSize(10f);

		YAxis leftAxis = mChart.getAxisLeft();

		leftAxis.setLabelCount(3, false);
		leftAxis.setAxisMaxValue(6f);

		leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
		leftAxis.setSpaceTop(15f);
		leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
		leftAxis.setTextColor(getResources().getColor(
				R.color.statis_reword_color));
		leftAxis.setTextSize(12f);

		YAxis rightAxis = mChart.getAxisRight();
		rightAxis.setEnabled(false);

		Legend l = mChart.getLegend();
		l.setEnabled(false);

	}

	protected void showChart(BarChart mChart, List<GrowRewardAndMoveInfo> infos2) {
		BarData data = getPieData(mChart,infos2);
		mChart.setData(data);
		mChart.invalidate();
		mChart.animateY(300);

	}

	private BarData getPieData(BarChart mChart,
			List<GrowRewardAndMoveInfo> statisticsList) {
		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<BarEntry> yValues = new ArrayList<BarEntry>(); // yVals用来表示封装每个饼块的实际数据

		ArrayList<Float> y = new ArrayList<Float>();
		for (int i = 0; i < statisticsList.size(); i++) {

			xValues.add(statisticsList.get(i).desc);
			yValues.add(new BarEntry(NumberFormatUtil
					.getFloatFromString(statisticsList.get(i).data), i));
			y.add(NumberFormatUtil
					.getFloatFromString(statisticsList.get(i).data));
			/*
			 * xValues.add(statisticsList.get(i).desc); yValues.add(new
			 * BarEntry(NumberFormatUtil
			 * .getFloatFromString(statisticsList.get(i).data)+i, i));
			 */

		}
		Collections.sort(y);
		YAxis leftAxis = mChart.getAxisLeft();
		float maxValue = y.get(y.size() - 1);
		int labelCount = 6;
		if (maxValue < 10) {
			maxValue = 10;
			leftAxis.setLabelCount(labelCount, true);
		} else {

			leftAxis.setLabelCount(8, false);

		}

		leftAxis.setAxisMaxValue(maxValue);

		BarDataSet set1;

		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 图例颜色
		colors.add(Color.rgb(89, 115, 173));
		colors.add(Color.rgb(49, 223, 187));
		colors.add(Color.rgb(135, 179, 78));
		colors.add(Color.rgb(44, 158, 137));
		colors.add(Color.rgb(237, 149, 63));
		if(yValues.size()>5){
			int r=0;
			int g=0;
			int b=0;
			for(int i=5;i<yValues.size();i++){
				r=(int) (Math.random()*255+1);
				g=(int) (Math.random()*255+1);
				b=(int) (Math.random()*255+1);
				colors.add(Color.rgb(r, g, b));
			}
		}
		set1 = new BarDataSet(yValues, "");
		set1.setBarSpacePercent(35f);

		set1.setColors(colors);

		ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
		dataSets.add(set1);

		BarData data = new BarData(xValues, dataSets);
		data.setValueTextSize(10f);
		data.setValueFormatter(new LargeValueFormatter());

		return data;
	}
	
	/**
	 * 为了实现界面的切换
	 * 
	 * @author smile_x
	 * 
	 */
	class TreeRefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MContants.REFRESH_FILETREE_ACTION)) {
				
			} else if (intent.getAction().equals(
					MContants.CHANGE_CURRENT_CHILD_ACTION)) {

				ChildBean myChild = (ChildBean) intent
						.getSerializableExtra(MContants.CHANGE_CURRENT_CHILD_DATAS);
				setMyclassStudentsWindow(myChild);
			}
		}
	}
	private void setMyclassStudentsWindow(ChildBean myChild) {
		myStudentsWindow = null;
		List<MyClassStudent> dbStudents = cupboard().withDatabase(sqlDb)
				.query(MyClassStudent.class)
				.withSelection("class_id = ?", mSpUtil.getChildClassId())
				.list();
		myStudentsWindow = new ClassWithStudentsWindow(this, myChild,
				dbStudents, this);
	}
	
	@Override
	public void onSelectResult(int type, String className,
			MyClassStudent selected) {
		this.type=type;
		
		if (type == 1) {
			/*tv_title.setText(className);
			student_id="0";
			mChart_move.setVisibility(View.GONE);
			mChart_reward.setVisibility(View.GONE);
			mRadarChart_move.setVisibility(View.VISIBLE);
			mRadarChart_reward.setVisibility(View.VISIBLE);*/
		} else {
			tv_title.setText(selected.student_name);
			student_id=selected.student_id;
			mChart_move.setVisibility(View.VISIBLE);
			mChart_reward.setVisibility(View.VISIBLE);
			mRadarChart_move.setVisibility(View.GONE);
			mRadarChart_reward.setVisibility(View.GONE);
		}
		onData();
		
	}
	private void showChart(RadarChart mChart,
			List<GrowRewardAndMoveInfo> statisticsList2) {

		RadarData data = getPieData(statisticsList2);

		mChart.setDescription("");

		mChart.setRotationEnabled(false);

		mChart.setWebLineWidth(1.5f);
		mChart.setWebColor(Color.LTGRAY);
		mChart.setWebLineWidthInner(0.75f);
		mChart.setWebAlpha(100);
		mChart.setData(data);
		mChart.invalidate();

		mChart.animateXY(1400, 1400, Easing.EasingOption.EaseInOutQuad,
				Easing.EasingOption.EaseInOutQuad);

		XAxis xAxis = mChart.getXAxis();
		// xAxis.setTypeface(tf);
		xAxis.setTextSize(9f);

		YAxis yAxis = mChart.getYAxis();
		// yAxis.setTypeface(tf);
		yAxis.setLabelCount(6, true);
		yAxis.setTextSize(0f);
		yAxis.setTextColor(Color.parseColor("#00DEDEDE"));
		yAxis.setAxisMinValue(0f);

		Legend l = mChart.getLegend();
		l.setPosition(LegendPosition.LEFT_OF_CHART);
		// l.setTypeface(tf);
		l.setXEntrySpace(7f);
		l.setYEntrySpace(5f);
		mChart.animate();
	}

	/**
	 * 
	 * @param count
	 *            分成几部分
	 * @param range
	 */

	private RadarData getPieData(List<GrowRewardAndMoveInfo> statisticsList) {

		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<Entry> yValues = new ArrayList<Entry>(); // yVals用来表示封装每个饼块的实际数据
		ArrayList<Entry> yValues2 = new ArrayList<Entry>(); // yVals用来表示封装每个饼块的实际数据

		for (int i = 0; i < statisticsList.size(); i++) {
			GrowData data = statisticsList.get(i).growdata;
			if (data != null) {
				xValues.add(statisticsList.get(i).desc);

				yValues.add(new Entry(NumberFormatUtil
						.getFloatFromString(data.grade), i));

				yValues2.add(new Entry(NumberFormatUtil
						.getFloatFromString(data.cls), i));

			}

		}

		// y轴的集合
		RadarDataSet pieDataSet = new RadarDataSet(yValues, "年级获奖量");// "Quarterly Revenue 2014"/*显示在比例图上*/);
		pieDataSet.setColor(Color.rgb(232, 52, 40));
		// pieDataSet.setFillColor(ColorTemplate.VORDIPLOM_COLORS[0]);
		pieDataSet.setDrawFilled(true);
		pieDataSet.setLineWidth(2f);

		RadarDataSet pieDataSet2 = new RadarDataSet(yValues2, "班级获奖量");// "Quarterly Revenue 2014"/*显示在比例图上*/);
		Log.e("===", yValues.toString());

		pieDataSet2.setColor(Color.rgb(40, 167, 225));
		// pieDataSet2.setFillColor(colors);
		pieDataSet2.setDrawFilled(true);
		pieDataSet2.setLineWidth(2f);

		ArrayList<RadarDataSet> sets = new ArrayList<RadarDataSet>();
		sets.add(pieDataSet);
		sets.add(pieDataSet2);

		RadarData data = new RadarData(xValues, sets);

		data.setValueTextSize(8f);
		data.setValueFormatter(new LargeValueFormatter());

		return data;
	}


}
